<template>
  <el-row>
    <el-col :span="24">
      <Portlet title="订单信息" :show-title="false">
        <el-form label-position="left" label-width="120px">
          <el-col :span="24">
            <span><span style="font-size: 20px; font-weight: 500;">{{biddingInfo.orderNo}}</span><span style="padding: 0 15px 0 15px">|</span><truncate :value="biddingInfo.consigneProvince + biddingInfo.consigneCity + biddingInfo.consigneDistrict + biddingInfo.consigneAddress" :maxLength="24"></truncate></span>
          </el-col>
          <el-col :lg="8" :md="12"  :xl="6">
            <el-form-item label="业务类型：">
              <span>{{ biddingInfo.business }}</span>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :xl="6">
            <el-form-item label="服务类型：">
              <span>{{ chOrder.service }}</span>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12"  :xl="6">
            <el-form-item label="收件人：">
              <span>{{ biddingInfo.consigneName }}</span>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12"  :xl="6">
            <el-form-item label="收件电话：">
              <span>{{ biddingInfo.consignePhone }}</span>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12"  :xl="6">
            <el-form-item label="总体积：">
              <span>{{ chOrder.totalVolume | decimalNumFilter}} m³</span>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12"  :xl="6">
            <el-form-item label="总包件：">
              <span>{{ chOrder.totalPackage}} 件</span>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :xl="6">
            <el-form-item label="总重量：">
              <span>{{ chOrder.totalWeight | decimalNumFilter}} kg</span>
            </el-form-item>
          </el-col>
        </el-form>
      </Portlet>
      <Portlet title="商品信息" style="position:relative;">
        <el-form>
          <el-row :gutter="10">
            <el-col :span="12" v-for="(good, index) in productExtBeans" :key="index">
              <el-row>
                <el-col :span="12">
                  <el-form-item >
                    <Upload-image :formData="{}" :showPictureNum="true" :readonly="true" :value="handleJsonStringArr(good.pictureId)"></Upload-image>
                  </el-form-item>

                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <p> 商品类别：{{ good.big_class}} {{good.middle_class}}</p>
                    <p> 商品名称：{{ good.productName }}</p>
                    <p> 商品数量：{{ good.proudctNum }}</p>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

        </el-form>
      </Portlet>
      <Portlet title="师傅报价" :show-title="false">
        <table class="order-table">
          <tr>
            <td align="center" style="padding-left: 5px; width: 15%">
              <img :src="'/api/ms-mongodb/file/download?fileId=' + biddingData.businessImg" style="width: 150px; height: 150px; border-radius: 50%"/>
            </td>
            <td width="35%">
              <div class="marginBottom8">
                {{biddingData.people}}
                <el-tooltip v-if="biddingData.isAuthention == 1" class="biddingData" effect="dark" content="已通过实名认证" placement="top-start">
                  <img style="no-repeat: center; height: 16px; width: 20px" src="/static/images/faHuoBao/certification.png" alt="实名认证" title="已通过实名认证" />
                </el-tooltip>
                <el-tooltip v-if="biddingData.isAuthention !== 1" class="biddingData" effect="dark" content="未实名认证" placement="top-start">
                  <img style="no-repeat: center; height: 16px; width: 20px" src="/static/images/faHuoBao/Unproven.png" alt="未实名认证" title="未实名认证"/>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="carContent" placement="top-start" style="margin-top: 5px">
                  <img style="no-repeat: center; height: 14px; width: 20px" src="/static/images/faHuoBao/car.png" alt="车辆" :title="carContent" />
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="areaContent" placement="top-start">
                  <img style="no-repeat: center; height: 16px; width: 20px" src="/static/images/faHuoBao/warehouse.png" alt="仓库" :title="areaContent" />
                </el-tooltip>
              </div>
              <div class="marginBottom8">
                <span class="shiFuAddress">{{biddingData.nature}}</span><span v-if="biddingData.address"> | {{biddingData.address}} </span>
              </div>
              <div class="marginBottom8">
                <el-tooltip v-if="biddingData.favorTMJD == 1" class="item" effect="dark" content="支持汪师傅核销" placement="right">
                  <img style="no-repeat: center; height: 22px; width: 46px" src="/static/images/faHuoBao/wangshifu.png" alt="汪师傅" title="支持汪师傅核销" />
                </el-tooltip>
                <el-tooltip v-if="biddingData.favorTMJD == 1" class="item" effect="dark" content="支持喵师傅核销" placement="right">
                  <img style="no-repeat: center; height: 22px; width: 46px" src="/static/images/faHuoBao/miaoshifu.png" alt="喵师傅" title="支持喵师傅核销" />
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="服务承诺" placement="right">
                  <img style="no-repeat: center; height: 22px; width: 61px" src="/static/images/faHuoBao/ServiceCommitment.png" alt="服务承诺" title="服务承诺"  @click="pledge()"/>
                </el-tooltip>
              </div>
              <div class="marginBottom8">
                <span>好评率：{{fhbWorkerCount.applauseRate}}%</span><span style="margin-left: 20px;">总单数：{{fhbWorkerCount.finishNum}}</span><span style="margin-left: 20px;">投诉数：{{fhbWorkerCount.complainNum}}</span>
              </div>
            </td>
            <td align="center" width="25%">
              <div class="cell-center">
                <div>师傅报价</div>
                <div><span style="font-size: 36px;" class="font-red">￥{{biddingData.price}}</span></div>
                <div>报价留言：<truncate :value="biddingData.memo" :maxLength="112"></truncate></div>
              </div>
            </td>
            <td align="center" width="25%">
              <div class="cell-center">
              </div>
            </td>
          </tr>
        </table>
      </Portlet>
      <Portlet title="支付方式" :show-title="true">
        <el-form :model="model" ref="form">
          <el-col :span="24" style="text-align: center; border-bottom: 1px dashed #C0CCDA;">
            <el-form-item
              prop="paymentType"
              :rules="[{required: true, message:'支付方式必须', trigger: 'change'}]"
            >
              <el-radio-group v-model="model.paymentType">
                <el-tooltip :key="index"  v-for="(item, index) in computedPaymentTypes" :disabled="!item.tip" :content='item.tip'>
                  <el-radio-button :label="item.value" :disabled="item.disabled">
                    {{item.text}}
                  </el-radio-button>
                </el-tooltip>
              </el-radio-group>
              <p>余额：{{balance | decimalNumFilter}} 元</p>
            </el-form-item>
            <div></div>
          </el-col>
        </el-form>
        <el-col :span="24" style="text-align: center; margin-top: 15px;">
          <p>金&nbsp;&nbsp;额：{{biddingData.price | decimalNumFilter}}元</p>
          <p>优&nbsp;&nbsp;惠：{{ - discount | decimalNumFilter}}元</p>
          <p>总&nbsp;&nbsp;计：{{lastMoney | decimalNumFilter}}元</p>
          <el-button type="button" class="btn btn-primary btn-lg green ladda-button" data-style="zoom-out" :loading="btnLoading" @click="payment($event)">确认支付</el-button>
        </el-col>
        <div class="clearfix"></div>
      </Portlet>
    </el-col>
    <el-dialog
      title="温馨提示"
      :visible.sync="paymentState"
      width="30%"
      center
    >
      <div style="text-align:center">恭喜您支付成功！本页面即将在3秒后跳转{{routeName === 'myOrdersPendingPayment' ? '待付款' : '报价'}}列表</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="btnDialog">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="温馨提示"
      :visible.sync="payDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="30%"
      center
    >
      <div style="text-align:center" v-if="!disabledBtn">请您在新打开的页面完成支付?</div>
      <div style="text-align:center" v-if="disabledBtn">
        <b style="font-size: 16px;">订单支付状态暂时无法确认</b>
        <p>尊敬的客户你好，很抱歉我们暂时无法确认您的支付结果,<br>
          建议您等待五分钟后再查看支付结果</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!disabledBtn" @click="unsuccessful">支付遇到问题</el-button>
        <el-button type="primary" v-if="!disabledBtn" @click="successful" :disabled="disabledBtn">{{ disabledBtn ? '等待支付结果' : '已经完成支付' }}</el-button>
        <el-button type="primary" v-if="disabledBtn" @click="btnDialog"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="钱包密码"
      :visible.sync="showWalletPay"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="20%"
      center
      >
      <div style="text-align: center">
        <el-input v-model="walletPwd" type="password" :maxlength="6" />
        <span class="font-red">{{error_message}}</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showWalletPay = false">取 消</el-button>
        <el-button type="primary" @click="walletpay" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
    <div v-html="htmltext"></div>
  </el-row>
</template>
<script>
import {dotData, confirm, handleJsonStringArr, alert} from '@/utils'
import {unixTimestampFilter, decimalNumFilter} from '@/filters'
import {payOmsTypes} from '@/utils/selectOptions'
import {mapActions, mapGetters} from 'vuex'
export default {
  name: 'expatriatePayment',
  components: {
  },
  data() {
    return {
      id: this.$route.params.id,
      orderId: this.$route.query.orderId,
      totalMoney: 0,
      detail: {},
      biddingInfo: {},
      biddingData: {},
      paymentTypes: [],
      model: {
        paymentType: ''
      },
      htmltext: '',
      routeName: this.$route.name,
      routeNextPath: '',
      paymentState: false,
      payDialog: false,
      disabledBtn: false,
      timer: 3000,
      btnLoading: false,
      balance: 0,
      showWalletPay: false,
      walletPwd: '',
      error_message: '',
      loading: false,
      discount: 0
    }
  },
  watch: {
    'walletPwd'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.error_message = ''
      if (this.loadding) {
        this.loadding = false
      }
    },
    'lastMoney'(val, oldVal) {
      if (val === 0) {
        this.model.paymentType = '3'
      }
    }
  },
  filters: {
    unixTimestampFilter,
    decimalNumFilter
  },
  computed: {
    chOrder() {
      return dotData(this.detail, 'chOrder') || {}
    },
    chOrderConsigneeInfo() {
      return dotData(this.detail, 'chOrderConsigneeInfo') || {}
    },
    fhbWorkerCount() {
      return dotData(this.biddingData, 'fhbWorkerCount') || {}
    },
    productExtBeans() {
      return dotData(this.detail, 'productExtBeans') || {}
    },
    carContent() {
      if (this.biddingData.carsHold) {
        return '配送车辆：' + this.biddingData.cars + '辆'
      } else {
        return '配送车辆：0辆'
      }
    },
    areaNum() {
      return dotData(this.biddingData, 'area') || 0
    },
    areaContent() {
      return '仓库：' + this.areaNum + '㎡'
    },
    lastMoney: function() {
      let lastMoney = this.biddingData.price - this.discount
      return decimalNumFilter(lastMoney)
    },
    cantWalletPay: function() {
      if (this.balance < this.lastMoney) {
        return true
      } else {
        return false
      }
    },
    computedPaymentTypes() {
      return this.paymentTypes.map(v => {
        v = Object.assign({}, v)
        // 余额为零 禁用 支付宝微信
        if (this.lastMoney === 0) {
          if (['aliPay', 'weChatPay'].indexOf(v.value) >= 0) {
            v.disabled = true
          }
        }
        // 余额不足 禁用钱包余额
        if (this.cantWalletPay) {
          if (v.value === '3') {
            v.disabled = true
          }
        }

        // // 配置禁用支付宝
        // if (this.GET_GLOBAL_CONFIG('aliPayPC') === false) {
        //   if (v.value === '1') {
        //     v.disabled = true
        //     v.tip = '维护中请稍后再试'
        //   }
        // }
        // // 配置禁用微信
        // if (this.GET_GLOBAL_CONFIG('weChatPayPC') === false) {
        //   if (v.value === '2') {
        //     v.disabled = true
        //     v.tip = '维护中请稍后再试'
        //   }
        // }
        // // 配置禁用钱包余额
        // if (this.GET_GLOBAL_CONFIG('walletPC') === false) {
        //   if (v.value === '3') {
        //     v.disabled = true
        //     v.tip = '维护中请稍后再试'
        //   }
        // }
        return v
      })
    },
    ...mapGetters(['GET_GLOBAL_CONFIG'])
  },
  created() {
    if (this.routeName === 'expatriateOfferingPayment') {
      this.routeNextPath = '/ss-oms/orders/expatriate/offering/index'
    } else {
      this.routeNextPath = '/ss-oms/orders/expatriate/pending/index'
    }
    // 基本信息
    this.getDetail()
    this.getBiddingInfo()
    // 师傅信息
    this.getBiddingData()
    // 支付方式
    this.createPaymentTypes()
    // 获取钱包余额
    this.getWallet()
  },
  methods: {
    handleJsonStringArr,
    // 获取支付方式
    createPaymentTypes() {
      payOmsTypes().then(arr => {
        this.paymentTypes = arr
      })
    },
    // 更换师傅
    changeWorker() {
      this.setCloseRoute({path: this.$route.fullPath})
      this.setRefreshRoute({path: '/ss-fhb/myOrders/offering/show/' + this.id})
    },
    // 账户余额
    getWallet() {
      this.$ajax.get('/ms-user-wallet/wallet/home-page').then(response => {
        let success = dotData(response, 'success')
        if (success) {
          this.balance = dotData(response, 'data.balance')
        }
      })
    },
    // 竞价中信息
    getBiddingInfo() {
      this.$ajax.get('/ms-terminal-order/bidding/bidding-order-info', {orderId: this.orderId}).then(response => {
        this.biddingInfo = response.data
      })
    },
    // 报价师傅
    getBiddingData() {
      this.$ajax.get('/ms-terminal-order/bidding/bidded-order', {orderId: this.orderId}).then(response => {
        this.biddingData = response.data
      })
    },
    // 订单信息
    getDetail() {
      this.$ajax.get('/ms-terminal-order/orderData/getOrderDatails', {orderId: this.orderId}).then(response => {
        if (!response.data) {
          return
        }
        this.detail = response.data || {}
      })
    },
    payment($event) {
      if (!this.model.paymentType) {
        alert('请选择支付方式')
      } else {
        // 钱包余额支付
        if (this.model.paymentType === '3') {
          this.showWalletPay = true
          this.walletPwd = ''
        } else {
          // 在线支付
          const newWindow = window.open('/static/pay.html')
          // let _this = this
          this.$refs.form.validate().then((result) => {
            if (result) {
              this.btnLoading = true
              this.$ajax.post('/ms-terminal-order/bidding/pay', {
                orderId: this.orderId,
                payType: this.model.paymentType
              }).then(response => {
                const success = dotData(response, 'success')
                if (success) {
                  let temp = `<!DOCTYPE html>
              <html lang="en">
              <head>
                  <meta charset="UTF-8">
                  <title>Title</title>
              </head>
              <body>
              ${response.data.sHtmlText}
              </body>
              </html>
              `
                  newWindow.document.write(temp)
                  newWindow.focus()
                  this.payDialog = true
                  this.disablesdBtn = false
                } else {
                  newWindow.close()
                  this.unsuccessful()
                }
              }).catch(() => {
                newWindow.close()
                this.unsuccessful()
              })
            }
          })
        }
      }
    },
    // 余额支付
    walletpay() {
      this.loading = true
      this.$ajax.post('/ms-terminal-order/bidding/balance-pay', {
        orderId: this.orderId,
        password: this.walletPwd
      }).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          confirm('支付成功，请进入支付管理界面查看支付信息', '提示', {
            type: 'success'
          }).finally(_ => {
            this.btnDialog() // 刷新页面到父页面
          })
          this.showWalletPay = false
          this.walletPwd = ''
        } else {
          this.error_message = dotData(response, 'error')
        }
        this.loading = false
      })
    },
    // 在线支付
    goPay() {
      this.$nextTick(_ => {
        document.getElementById('submit').submit()
        this.payDialog = true
        this.disabledBtn = false
      })
    },
    successful() {
      // this.disabledBtn = true
      let idArr = []
      idArr = [this.id]
      let orderParam = {
        list: [idArr.join(',')]
      }
      this.$ajax.post('/ms-fahuobao-json-view/FhbOrder/finByOrderPayStatus', orderParam).then(response => {
        const success = dotData(response, 'data')
        if (success) {
          this.paymentState = true
          this.payDialog = false
          setTimeout(() => {
            this.btnDialog() // 刷新页面到父页面
          }, 3000)
        } else {
          this.disabledBtn = true
        }
      })
    },
    btnDialog() {
      this.payDialog = false
      this.paymentState = false
      this.$router.push({path: '/redirect' + this.routeNextPath})
    },
    unsuccessful() {
      this.payDialog = false
      this.$confirm('很抱歉！支付失败。您可以尝试重新支付或联系客服。', '温馨提示', {
        confirmButtonText: '重新支付',
        cancelButtonText: '联系客服',
        closeOnClickModal: false,
        type: 'warning',
        center: true
      }).then(() => {
        // 重新支付
        // this.goPay()
        this.Payment()
      }).catch(() => {
        // 联系客服
        this.btnLoading = false
      })
    },
    pledge() {
      this.BighomeServiceCommitment = this.biddingData.bighomeServiceCommitment
      let pledgeStr = `<p>1.` + this.BighomeServiceCommitment.carrSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.freeForCarry + `</p>
                       <p>2.` + this.BighomeServiceCommitment.overmileSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.coastForOvermile + `</p>
                       <p>3.` + this.BighomeServiceCommitment.storageSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.freeForStorage + `</p>
                       <p>4.` + this.BighomeServiceCommitment.uniformSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.serviceOnUniform + `</p>
                       <p>5.` + this.BighomeServiceCommitment.basicSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.basicCommitment + `</p>`
      this.$alert(pledgeStr, '师傅服务承诺', {
        showConfirmButton: '关闭',
        dangerouslyUseHTMLString: true
      })
    },
    ...mapActions([
      'setRefreshRoute',
      'setCloseRoute',
      'setPageBar'
    ])
  }
}
</script>
